package pri.lt.parser;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.sun.webkit.WebPage;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import pri.lt.Constants;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class QQNewParser implements Parser {

    static QQNewParser sInstance;

    public synchronized static Parser getInstance() {
        if (sInstance == null) {
            sInstance = new QQNewParser();
        }
        return  sInstance;
    }

    @Override
    public ParserResult parse(String url) {

        WebDriverWrapper webDriverWrapper = WebDriverManager.getWebDriverWrapper();
        try {
            String publishTime = null;

            webDriverWrapper.getWebDriver().get(url);
            String pageXml = webDriverWrapper.getHtmlExcuteJs();//直接将加载完成的页面转换成xml格式的字符串


            Document doc = Jsoup.parse(pageXml, url);


            Object publishTimeObject = null;


            String srcTimeText = doc.select("div.a-src-time").select("a").text();
            try {
                publishTime = srcTimeText.substring(srcTimeText.indexOf(" ")).trim();
            } catch (Exception e) {

            }

            if (publishTime == null || publishTime.trim().length() == 0) {
                try {

                    String year = doc.select("div.year.through").text();
                    String monthDay = doc.select("div.md").text();
                    String time = doc.select("div.time").text();
                    String month = monthDay.split("/")[0];
                    String day = monthDay.split("/")[1];
                    if (month.length() == 1) {
                        month = "0" + month;
                    }
                    if (day.length() == 1) {
                        day = "0" + day;
                    }
                    publishTime = year + "-" + month + "-" + day + " " + time + ":00";
                } catch (Exception e) {

                }
            }

            if (publishTime == null || publishTime.trim().length() == 0) {

                webDriverWrapper.release();
                return null;
            }

            System.out.println("litao url publish at " + publishTime);

            Element contentElement = doc.select("div.content-article").first();
            if (contentElement == null) {
                webDriverWrapper.release();
                return null;
            }

            String title = null;
            try {
                Element titleElement = doc.select("div.LEFT").first();
                title = titleElement.select("h1").text();
            } catch (Exception e) {

            }
            ParserResult parserResult = new ParserResult();

            parserResult.title = title;
            parserResult.content = contentElement.html();
            //parserResult.allHtml = pageXml;
            try {
                parserResult.publishTime = new SimpleDateFormat(Constants.DATETIME_FORMAT).parse(publishTime);

            } catch (Exception e) {

                e.printStackTrace();
            }


            try {
                WebElement commentLinkElement = webDriverWrapper.getWebDriver().findElement(By.id("cmtLink"));
                parserResult.commentUrl = commentLinkElement.getAttribute("href");
            } catch (NoSuchElementException e) {
                try {
                    webDriverWrapper.getWebDriver().switchTo().frame("commentIframe");
                    WebElement commentLinkElement = webDriverWrapper.getWebDriver().findElement(By.id("cmtLink"));
                    parserResult.commentUrl = commentLinkElement.getAttribute("href");
                } catch (Exception e2) {
                    System.out.println("get comment link exception " + url);
                    System.out.println("getHotCommentResult get Exception pagehtml = " + pageXml);
                    webDriverWrapper.release();
                }
            } catch (Exception e) {
                System.out.println("get comment link exception " + url);
                System.out.println("getHotCommentResult get Exception pagehtml = " + pageXml);
                return null;
            } finally {

                webDriverWrapper.release();
            }

            Elements elements = contentElement.select("img[src]");//获取到的值为所有的<img src="...">

            int i = 0;
            for (Element element : elements) {
                try {

                    String imgUrl = element.attr("src");//获取到src的值
                    if (imgUrl != null) {
                        if (imgUrl.startsWith("http")) {

                        } else {
                            if (url.startsWith("https")) {
                                imgUrl = "https:" + imgUrl;
                            } else if (url.startsWith("http")) {
                                imgUrl = "http:" + imgUrl;
                            }
                        }
                        URL imgHttpUrl = new URL(imgUrl);
                        URLConnection connection = imgHttpUrl.openConnection();
                        connection.setDoOutput(true);
                        BufferedImage image = ImageIO.read(connection.getInputStream());
                        int srcWidth = image .getWidth();      // 源图宽度
                        int srcHeight = image .getHeight();    // 源图高度

                        if (srcWidth > 0 && srcHeight > 0 && srcWidth >= 500) {
                            float radio = ((float)srcHeight) / ((float)srcWidth);
                            if (radio > 0.25 && radio <= 2) {
                                parserResult.thumbnailUrl = imgUrl;
                                break;
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }



            if (!parserResult.isValid()) {
                webDriverWrapper.release();
                return null;
            }


            return parserResult;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webDriverWrapper.release();
        }
        return null;
    }

    @Override
    public HotCommentResult getHotCommentResult(String url,  Parser.ParserResult parserResult) {
        String commentCountString = "";
        WebDriverWrapper webDriverWrapper = WebDriverManager.getWebDriverWrapper();
        List<HotComment> comments = new ArrayList<>();
        String pagehtml = "";
        try {

//            webDriverWrapper.getWebDriver().manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
//            webDriverWrapper.getWebDriver().manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
            webDriverWrapper.getWebDriver().get(parserResult.commentUrl);
            pagehtml = webDriverWrapper.getWebDriver().getPageSource();
            webDriverWrapper.getWebDriver().switchTo().frame("commentIframe");
            WebElement commentNumElement = webDriverWrapper.getWebDriver().findElement(By.id("J_CommentTotal"));
            commentCountString = commentNumElement.getText();

            List<WebElement> commentElements =  webDriverWrapper.getWebDriver().findElements(By.cssSelector("div.comment-content.J_CommentContent"));
            for (int i = 0; i < commentElements.size(); i ++) {
                if (i == 10) {
                    break;
                }
                HotComment hotComment = new HotComment();
                hotComment.content = commentElements.get(i).getText();
                comments.add(hotComment);
            }
        } catch (Exception e) {
            System.out.println("getHotCommentResult get Exception url = " + url);
            System.out.println("getHotCommentResult get Exception pagehtml = " + pagehtml);
            return null;
        } finally {

            webDriverWrapper.release();
        }
        int commentCount = 0;
        try {
            commentCount = Integer.parseInt(commentCountString);
        } catch (Exception e) {

        }
        boolean isHot = false;
        if (commentCount > 50)  {
            isHot = true;
        } else if (commentCount > 10) {
            Date now = new Date();
            long publishElapseTime = now.getTime() - parserResult.publishTime.getTime();
            long pushLishElapseHour = publishElapseTime / (1000 * 60 * 60);
            if (commentCount > (pushLishElapseHour + 1) * 10) {
                isHot = true;
            }
        }

        HotCommentResult hotCommentResult = new HotCommentResult();
        hotCommentResult.isHot = isHot;
        hotCommentResult.commentCount = commentCount;
        hotCommentResult.crawlerReplyRankCount = (double) commentCount / (double)50;
        hotCommentResult.comments = comments;
        return hotCommentResult;
    }

    @Override
    public boolean isDomainSupport(String url) {
        return url != null && url.contains("qq.com") && !url.contains("weixin.qq.com");
    }

    @Override
    public boolean isUrlCanParse(String url) {
        return url != null && (url.startsWith("https://new.qq.com/")
                || url.startsWith("http://new.qq.com/") && !url.contains("weixin.qq.com"));
    }

    @Override
    public boolean isDomainDirectory(String url) {
        return url != null && (url.endsWith("qq.com") || url.endsWith("qq.com/"));
    }
}
